package com.forum.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * @program: back-on-backend-code
 * @description: 数据库密码加密
 * @author: 张继成
 * @create: 2024-03-18 20:46
 **/

public class DruidEncryptUtil {
    private static final String publicKey;

    private static final String privateKey;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            // 私钥
            privateKey = keyPair[0];
            // 公钥
            publicKey = keyPair[1];
            System.out.println("私钥：" + privateKey);
            System.out.println("公钥：" + publicKey);

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    public static String encrypt(String plainText ) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt:"+encrypt);
        return encrypt;
    }

    public static String decrypt(String encrypt) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, encrypt);
        System.out.println("decrypt:"+ decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("root");
        System.out.println("encrypt:"+ encrypt);
    }
}
